package com.java.shop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.shop.product.dao.BrandDao;
import com.java.shop.product.entity.BrandEntity;
import com.java.shop.product.entity.CategoryBrandRelationEntity;
import com.java.shop.product.service.BrandService;
import com.java.shop.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("first_letter",key).or().like("name",key);
        }

        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params),wrapper);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        this.updateById(brand);
        //判断是否在关联分类表中有数据
        Integer brandRelationCount = categoryBrandRelationService.count(new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id",brand.getBrandId()));
        if(brandRelationCount == 0) return;
        if(!StringUtils.isEmpty(brand.getName())){
            QueryWrapper<CategoryBrandRelationEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("brand_id",brand.getBrandId());
            CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
            categoryBrandRelationEntity.setBrandName(brand.getName());
            categoryBrandRelationService.update(categoryBrandRelationEntity,wrapper);
            //TODO 跟新其他表对应的品牌字段
        }
    }
}